<?php

namespace App\Admin\Controllers;

use App\CommonSet;
use App\Tools\AliOss;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Box;
use App\Http\Controllers\Controller;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;

class CommonSetController extends Controller
{

    public function showCommonSet(){
        return Admin::content(function (Content $content){
            $content->header('通用设置');

            $commonSet = CommonSet::first();

            if($commonSet == null){
                $commonSet['recom_reward_state'] = 0;
                $commonSet['dy_code_state'] = 0;
                $commonSet['dy_code'] = '';
            }
            $form = new Form();
            $form->method('get');
            $state = [
                'on'  => ['value' => 1, 'text' => '开启', 'color' => 'success'],
                'off' => ['value' => 0, 'text' => '关闭', 'color' => 'default'],
            ];
            $form->switch('recom_reward_state', '激励广告')->states($state)->default($commonSet['recom_reward_state'])->help('开启后，首页进入详情弹出激励广告视频才可解锁');
            $form->switch('dy_code_state', '抖音口令')->states($state)->default($commonSet['dy_code_state'])->help('开启后，打开页面会自动复制抖音口令');
            $form->text('dy_code', '抖音口令码')->placeholder('输入抖音口令码')->default($commonSet['dy_code']);
            $form->action('updateCommonSet');

            $content->body(new Box('通用设置', $form));

        });
    }

    protected function updateCommonSet(Request $request)
    {
        $recom_reward_state = $request->get('recom_reward_state') == 'on' ? 1 : 0;
        $dy_code_state = $request->get('dy_code_state') == 'on' ? 1 : 0;
        $dy_code = $request->get('dy_code');

        $commonSet = CommonSet::first();
        if ($commonSet == null){
            $commonSet = new CommonSet();
        }

        $commonSet['recom_reward_state'] = $recom_reward_state;
        $commonSet['dy_code_state'] = $dy_code_state;
        $commonSet['dy_code'] = $dy_code;
        if($commonSet->save()){
            return <<<EOT
                <script type="text/javascript">
                    swal("更新成功");
                    setTimeout(function (){
						window.location.href = '/admin/commonset/showCommonSet';
					}, 1000);
                    
                </script>
EOT;
        }else{
            return <<<EOT
                <script type="text/javascript">
                	swal("更新失败");
                    setTimeout(function (){
						window.location.href = '/admin/commonset/showCommonSet';
					}, 1000);
                </script>
EOT;
        }
    }
}
